(()=>{
	const CONF_LAST_OPEN_PAGE = 'last_open_page';
	let lastViewPage = null;
	let currentViewPage = null;
	
	window.PageHelper = class PageHelper {
		static view(pageId) {
			if(window.SearchController && SearchController.isInSearch()) {
				SearchController.resetKeywordCount();
			}
			
			let pageModel = new PageModel;
			pageModel.load(pageId);
			
			if(!pageModel.getId()) {
				CoreHelper.alertError('此页面不存在');
				
				if(lastViewPage && lastViewPage != pageId) {
					this.view(lastViewPage);
				}
				
				return;
			}
			
			currentViewPage = pageId;
			lastViewPage = pageId;
			
			let allGroups = this.getPageGroupBlocks(pageId);
			let contentHtml = '';
			CoreHelper.PageTitleElement.html(pageModel.getName());
			CoreHelper.PageExportElement[0].setAttribute('data-page-id', pageId);
			
			for(let i=0; i<allGroups.length; i++) {
				contentHtml += BlockHelper.render(allGroups[i]);
			}
			
			CoreHelper.PageContentElement.html(contentHtml);
			
			if(window.SearchController && SearchController.isInSearch()) {
				SearchController.hideEmptyGroup().updateSearchKeyword();
			}
			
			if(!window.SearchController || !SearchController.isInSearch()) {
				ConfigModel.saveKeyValue(CONF_LAST_OPEN_PAGE, pageId);
			}
		}
		
		static getPageGroupBlocks(pageId) {
			let blockCollector = new BlockModelCollector;
			
			if(pageId) {
				blockCollector.where('page_id', pageId);
			}
			
			blockCollector.where(COL('type').eq(BlockModel.TYPE.GROUP)).sort('position', 'ASC');
			return blockCollector.load().get();
		}
		
		static exportPage(pageId) {
			if(!pageId) {
				return ;
			}
			let model = new PageModel();
			model.setId(pageId).load();
			
			if(!model.getId()) {
				CoreHelper.alertError('此记录不存在');
				return;
			}
			
			CoreHelper.copyValueAndTips(model.toString());
		}
		
		static getCurrentViewPage() {
			return currentViewPage;
		}
		
		static getLastPageId() {
			let id = ConfigModel.getKeyValue(CONF_LAST_OPEN_PAGE);
			return (new PageModel).load(id).getId();
		}
	};
	
	Core.setToParentWindow('PageHelper', PageHelper);
})();